package org.bai.miaoshaproject.controller;

import lombok.extern.slf4j.Slf4j;
import org.bai.miaoshaproject.error.BusinessException;
import org.bai.miaoshaproject.error.EmBusinessError;
import org.bai.miaoshaproject.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName BaseController
 *
 * @author Bai
 * @version 1.0
 * @date 2019/5/28 0028 上午 0:12
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public CommonReturnType handleException(HttpServletRequest request, HttpServletResponse response, Exception ex){
        Integer errCode = EmBusinessError.UNKNOWN_ERROR.getErrorCode();
        String errMsg = EmBusinessError.UNKNOWN_ERROR.getErrorMsg();
        if(ex instanceof BusinessException){
            BusinessException businessException = (BusinessException)ex;
            errCode = businessException.getErrorCode();
            errMsg = businessException.getErrorMsg();
        } else if(ex instanceof ServletRequestBindingException){
            errMsg = "URL绑定路由发生问题";
        } else if(ex instanceof NoHandlerFoundException){
            errMsg = "没有找到对应的访问路径";
        } else {
            log.error(ex.getMessage());
        }
        return CommonReturnType.creatError(errCode, errMsg);
    }
}
